/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gfs;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

/**
 *
 * @author Mark Vismonte
 * @author Joel Jauregui
 */

public class StrategoNetworkCom extends Object
    {
    public StrategoNetworkCom()
        {
        super();
        bd = null;
        s = null;
        oops = null;
        oips = null;
        oppsCoors = null;
        lastEvent = null;
        turn = false;
        }
    
    private void connect() throws IOException
        {
        String ipAddy = StrategoIO.getString("Enter the IP Address of "
             + "the other machine you would like to connect to");
        if (ipAddy == null)
            System.exit(1);
        s = new Socket(ipAddy, STRATEGO_GAME_PORT);
        turn = true;
        bd = new Board(false);
        temp = bd.drawBoard();
        }
    
    private void hostGame() throws IOException
        {
        s = (new ServerSocket(STRATEGO_GAME_PORT)).accept();
        oops = new ObjectOutputStream(s.getOutputStream());
        bd = new Board(true);
        temp = bd.drawBoard();
        oops.writeObject(temp);
        }
    
    public void init()
        {
        StrategoIO.infoMsg("Welcome to Network Stratego\n" +
                "By Mark Vismonte and Joel Jauregui", WINDOW_NAME);
        StrategoIO.infoMsg(MSG,WINDOW_NAME);
        int local = 0;
        local = StrategoIO.confirmMsg("Are you hosting?", "Hosting");
        // asks the user if they are the host of the game
        if (local == StrategoIO.CLOSED_OPTION)
            System.exit(1);
        if(local == StrategoIO.OPT_NO)
        // they are not the host the machine will then ask what the ip address
        // is that he/she wants to connect to and connect to that machine using
        // the stratego_game_port which is defined at 7777
            {
            try
                {
                connect();
                }
            catch (IOException ex) 
                {
                System.out.println(ex);
                System.exit(1);
                }
            }
        else
        // if they are the host then they will accept the call from the port
        // it will then create the ObjectOutputStream
            {
            try
                {
                hostGame();
                }
            catch (IOException ex) 
                {
                System.exit(1);
                }
            }
        StrategoIO.infoMsg("You are connected!", "Connected");
        }
    
    public boolean setUpPieces()
        {
        while (!bd.netBuddysSoldiersHaveCoordinates()) 
            {
            try 
                {
                System.out.println("Getting opponents soldiers");
                oips = new ObjectInputStream(s.getInputStream());
                oppsCoors = (int[]) (oips.readObject());
                if(oppsCoors != null)
                    {
                    Thread.sleep(100);
                    bd.setNetBuddyPieceCoordinate(oppsCoors);
                    oppsCoors = null;
                    }
                oops = new ObjectOutputStream(s.getOutputStream());
                oppsCoors = temp;
                oops.writeObject(oppsCoors);
                }//
            catch (Exception e)    
                {                
                System.err.println(e.getMessage());
                e.printStackTrace();
                }
            }
        lastEvent = new StrategoEvent(-1, -1);
        for (StrategoSoldier ss : bd.getNetworkPlayer().getSoldiers())
            {
            Coordinate old = ss.getCoordinate();
            Coordinate cd = bd.getCoordinate(old.getRow(), old.getCol());
            ss.setCoordinate(cd);
            ss.draw(false);
            }   
        StrategoPlayer plyer1 = bd.getNetworkPlayer();
        StrategoPlayer plyer2 = bd.getLocalPlayer();
        System.out.println("This player is host:" + plyer1.isHost());
        plyer1.insertSortSelection(true);
        plyer2.insertSortSelection(true);
        ArrayList<StrategoSoldier> list1 = plyer1.getSoldiers();
        ArrayList<StrategoSoldier> list2 = plyer2.getSoldiers();
        for(StrategoSoldier ss : list1)
            System.out.println("1 This soldier's hash is:" + ss.getCoordinate().hashCode());
        for(StrategoSoldier ss : list2)
            System.out.println("2 This soldier's hash is:" + ss.getCoordinate().hashCode());
        for(int x = 0; x < 4; x++)
            {
            for(int y = 0; y < 10; y++)
                bd.getMap()[x][y] = list1.get(x*10 + y);
            }        
        for(int x = 6; x < 10; x++)
            {
            for(int y = 0; y < 10; y++)
                bd.getMap()[x][y] = list2.get((x - 6)*10 + y);
            }        
        bd.redrawLines();
        return true;
        }
    
    public void netStrategoLoop()
        {
        while (!bd.winner) 
            {
            try 
                {
                System.out.println("Starting turn");
                if (bd.winner)
                    s.close();
                oips = new ObjectInputStream(s.getInputStream());
                Object obj = oips.readObject();
                System.out.println(obj);
                if (obj.getClass().equals(StrategoEvent.class))
                    {
                    lastEvent = (StrategoEvent) (obj);
                    System.out.println(lastEvent);
                    }
                while (lastEvent.ready) 
                    {
                    Thread.sleep(100);                    
                    lastEvent = bd.doTurn(lastEvent);
                    System.out.println("Finished Turn");
                    lastEvent.ready = false;
                    }
                oops = new ObjectOutputStream(s.getOutputStream());
                lastEvent.ready = true;
                oops.writeObject(lastEvent);
                System.out.println("Wrote Object to Stream");                
                }
            catch (Exception e)    
                {
                System.err.println(e);
                }
            }
        }
    
    private int[] oppsCoors;
    private int[] temp;
    private StrategoEvent lastEvent;
    //private boolean local;
    private boolean turn;
    private Board bd;
    private Socket s;
    private ObjectOutputStream oops;
    private ObjectInputStream oips;
    public static final int STRATEGO_GAME_PORT = 7777;
    public static final int STRATEGO_CHAT_PORT = 6666;
    public static String WINDOW_NAME = "Welcome to Stratego!";
    public static String MSG = "Created by: Mark Vismonte and Joey Jauregui\n" +
            "Date released: 6/2/08\n Rules to be inputed";
    }

class StrategoTestChat extends Object implements Serializable
    {
    public StrategoTestChat()
        {
        super();
        ready = true;
        st = "Hey!";
        }
    public String changeReady()
        {
        print();
        ready = !ready;
        String str =  StrategoIO.getString("Say something");
        st = str;
        return str;
        }
    public void print()
        {
        StrategoIO.infoMsg(st, "Messenger");
        }
    private String st;
    public boolean ready;
    }

